from flask import Blueprint, jsonify, request, render_template
from datetime import datetime
from app.model.models import Project, db

projects_bp = Blueprint('projects', __name__)

@projects_bp.route('/')
def projects_page():
    return render_template('projects.html')

@projects_bp.route('/list', methods=['GET', 'POST'])
def projects():
    if request.method == 'GET':
        projects = Project.query.all()
        return jsonify([{
            'id': p.id,
            'name': p.name,
            'description': p.description,
            'create_time': p.create_time
        } for p in projects])
    elif request.method == 'POST':
        data = request.get_json()
        project = Project(
            name=data['name'],
            description=data.get('description', ''),
            create_time=datetime.utcnow()
        )
        db.session.add(project)
        db.session.commit()
        return jsonify({'id': project.id}), 201

@projects_bp.route('/delete/<int:project_id>', methods=['DELETE'])
def project(project_id):
    project = Project.query.get_or_404(project_id)
    db.session.delete(project)
    db.session.commit()
    return '', 204
